package cn.lyd.system.service.impl;

import cn.lyd.base.until.BussinessException;
import cn.lyd.system.domain.Role;
import cn.lyd.system.mapper.RoleMapper;
import cn.lyd.system.service.IRoleService;
import cn.lyd.base.service.impl.BaseServiceImpl;
import jdk.nashorn.internal.ir.IfNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyd
 * @since 2023-01-03
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 添加角色重写：  要添加的表 t_role， t_role_menu， t_role_permission
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        //1.添加角色表
        super.add(role);
        //2.添加t_role_permission表
        if (role.getPermissions()!=null) {
            role.getPermissions().stream().forEach(permissionId -> roleMapper.addRolePermissionTable(role.getId(),permissionId) );
        }else {
            throw new BussinessException("请分配权限！");
        }
        //3.添加t_role_menu表
        if (role.getMenus()!=null) {
            role.getMenus().stream().forEach(menuId -> roleMapper.addRoleMenuTable(role.getId(),menuId));
        }else {
            throw new BussinessException("请分配角色！");
        }
    }

    /**
     * 删除角色重写 ：要删除的表 t_role， t_role_menu， t_role_permission
     * @param id  也就是role_id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        //1.删除t_role_menu表
        roleMapper.delRoleMenuTableByRoleId(id);
        //2.删除t_role_permission表
        roleMapper.delRolePermissionTableByRoleId(id);
        //3.删除角色表
        super.delete(id);
    }


    /**
     * 修改角色重写：要修改的表 t_role， t_role_menu， t_role_permission
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        //1.有id->修改role
        super.update(role);

        //2.删了中间表
        roleMapper.delRoleMenuTableByRoleId(role.getId());
        roleMapper.delRolePermissionTableByRoleId(role.getId());

        //3.添加t_role_permission表
        if (role.getPermissions()!=null) {
            role.getPermissions().stream().forEach(permissionId -> roleMapper.addRolePermissionTable(role.getId(),permissionId) );
        }else {
            throw new BussinessException("请分配权限！");
        }
        //4.添加t_role_menu表
        if (role.getMenus()!=null) {
            role.getMenus().stream().forEach(menuId -> roleMapper.addRoleMenuTable(role.getId(),menuId));
        }else {
            throw new BussinessException("请分配角色！");
        }


    }
}
